<template>
    <el-form-item :label="label" :prop="tag">
        <!-- 上传头像的进度条 -->
        <el-progress v-if="isUploading" type="circle" :percentage="percentage" :width="178"
            :status="percentage === 100 ? 'success' : undefined"></el-progress>
        <!-- 上传头像的框 -->
        <el-upload v-else class="avatar-uploader" action="/management/file/minio/upload" :show-file-list="false"
            :on-success="handleSuccess" :on-progress="handleProgress">
            <el-image fit="cover" v-if="modelValue" :src="modelValue" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
                <Plus />
            </el-icon>
        </el-upload>
    </el-form-item>
</template>

<script setup lang="ts" name="UploadImage">
import type { UploadProgressEvent } from 'element-plus';
import { ref } from 'vue';

defineProps(['label', 'tag', 'modelValue'])
const emit = defineEmits(['update:modelValue']);

const isUploading = ref(false)
const percentage = ref(0)

const handleProgress = (event: UploadProgressEvent) => {
    isUploading.value = true
    percentage.value = Math.floor(event.percent)
}

const handleSuccess = async (response: any) => {
    // 上传成功拿到文件名称
    const url = response.data
    emit('update:modelValue', url)
    isUploading.value = false
}
</script>

<style scoped lang="scss">
:deep(.avatar-uploader) {
    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }

    .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
        border-color: var(--el-color-primary);
    }
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>